package com.quality.web.controller.business;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.quality.business.domain.QualityGroup;
import com.quality.business.domain.QualityRule;
import com.quality.business.domain.QualityStatistics;
import com.quality.business.service.QualityGroupService;
import com.quality.business.service.QualityRuleService;
import com.quality.business.service.QualityStatisticsService;
import com.quality.common.annotation.Log;
import com.quality.common.core.controller.BaseController;
import com.quality.common.core.domain.AjaxResult;
import com.quality.common.core.page.TableDataInfo;
import com.quality.common.enums.BusinessType;
import com.quality.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @author hjh
 * @Description TODO
 * @createTime 2022年06月25日 18:14:00
 */
@PreAuthorize("@ss.hasAnyRoles('common,common_admin,admin')")
@RestController
@RequestMapping("/quality/rule")
public class QualityRuleController extends BaseController {

    @Autowired
    private QualityRuleService ruleService;
    @Autowired
    private QualityGroupService groupService;
    @Autowired
    private QualityStatisticsService statisticsService;

    @GetMapping("/list")
    public TableDataInfo list(Integer groupId){
        LambdaQueryChainWrapper<QualityRule> w = ruleService.lambdaQuery();
        if (ObjectUtil.isNotNull(groupId)){
            w.eq(QualityRule::getGroupId, groupId);
        }
        if (!getUserId().equals(1L)){
            w.eq(QualityRule::getUserId,getUserId());
        }
        startPage();
        List<QualityRule> list = w.list();
        for (QualityRule rule : list) {
            rule.setGroupName(groupService.getById(rule.getGroupId()).getGroupName());
        }
        return getDataTable(list);
    }


    @GetMapping("/byId")
    public AjaxResult byId(Integer id){
        return AjaxResult.success(ruleService.getById(id));
    }

    @Log(title = "质检规则管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody QualityRule rule){
        errIf(ObjectUtil.isNull(rule.getGroupId()),"分组不能为空");
        errIf(StrUtil.isEmpty(rule.getDatabase()),"数据库不能为空");
        errIf(StrUtil.isEmpty(rule.getTable()),"主题表名不能为空");
        errIf(StrUtil.isEmpty(rule.getField()),"字段名不能为空");
        errIf(ObjectUtil.isNull(rule.getRule()),"规则类型不能为空不能为空");
        errIf(rule.getRule().equals(4) && StrUtil.isEmpty(rule.getPatten()),"正则表达式不能为空");
        errIf(StrUtil.isEmpty(rule.getDescription()),"规则描述不能为空");
        rule.setUserId(getUserId());
        if (rule.getRule().equals(2) || rule.getRule().equals(3)){
            errIf(StrUtil.isEmpty(rule.getBegin()) || StrUtil.isEmpty(rule.getEnd()),"请输入数据范围");
            if (rule.getRule().equals(2)){
                try {
                    Double integer = Double.parseDouble(rule.getBegin());
                    Double integer1 = Double.parseDouble(rule.getEnd());
                } catch (Exception e) {
                    throw new ServiceException("请输入正确的数据范围");
                }
            }
        }

        ruleService.save(rule);
        return AjaxResult.success();
    }

    @Log(title = "质检规则管理", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody QualityRule rule){
        errIf(ObjectUtil.isNull(rule.getGroupId()),"分组不能为空");
        errIf(StrUtil.isEmpty(rule.getDatabase()),"数据库不能为空");
        errIf(StrUtil.isEmpty(rule.getTable()),"主题表名不能为空");
        errIf(StrUtil.isEmpty(rule.getField()),"字段名不能为空");
        errIf(ObjectUtil.isNull(rule.getRule()),"规则类型不能为空不能为空");
        errIf(StrUtil.isEmpty(rule.getDescription()),"规则描述不能为空");
        errIf(rule.getRule().equals(4) && StrUtil.isEmpty(rule.getPatten()),"正则表达式不能为空");
        if (rule.getRule().equals(2) || rule.getRule().equals(3)){
            errIf(StrUtil.isEmpty(rule.getBegin()) || StrUtil.isEmpty(rule.getEnd()),"请输入数据范围");
            if (rule.getRule().equals(2)){
                try {
                    Double integer = Double.parseDouble(rule.getBegin());
                    Double integer1 = Double.parseDouble(rule.getEnd());
                } catch (Exception e) {
                    throw new ServiceException("请输入正确的数据范围");
                }
            }
        }
        ruleService.updateById(rule);
        return AjaxResult.success();
    }

    @GetMapping("/enable")
    public AjaxResult enable(Integer id){
        QualityRule byId = ruleService.getById(id);
        byId.setIsEnable(!byId.getIsEnable());
        ruleService.updateById(byId);
        return AjaxResult.success();
    }

    @Log(title = "质检规则管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable("ids") Integer[] ids){
        List<Integer> list = Arrays.asList(ids);
        errIf(CollectionUtil.isEmpty(list),"请选择数据");
        ruleService.removeByIds(list);
        statisticsService.remove(statisticsService.lambdaQuery()
                .eq(QualityStatistics::getUserId,getUserId())
                .in(QualityStatistics::getRuleId,list).getWrapper());
        return AjaxResult.success();
    }
}
